package com.CuandoLlegaAndroid;

import com.CuandoLlegaAndroid.Custom.CustomToast;
import com.CuandoLlegaAndroid.Helpers.Utils;

import android.app.TabActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Resources;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.ViewFlipper;

public class Main extends TabActivity
// implements OnGestureListener
{

	private Intent mainConsultIntent;
	private GestureDetector gestureScanner;

	int current_tab;
	TabHost tabHost;

	// private GestureDetector gestureDetector;
	private Animation slideLeftIn;
	private Animation slideLeftOut;
	private Animation slideRightIn;
	private Animation slideRightOut;
	private ViewFlipper viewFlipper;
	private ImageView mainHeaderFav;
	private ImageView mainHeaderCon;

	private static final int SWIPE_MIN_DISTANCE = 120;
	private static final int SWIPE_MAX_OFF_PATH = 250;
	private static final int SWIPE_THRESHOLD_VELOCITY = 200;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		viewFlipper = (ViewFlipper) findViewById(R.id.flipper);
		mainHeaderFav = (ImageView) findViewById(R.id.mainHeaderFav);
		mainHeaderCon = (ImageView) findViewById(R.id.mainHeaderCon);
		slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.slide_left_in);
		slideLeftOut = AnimationUtils
				.loadAnimation(this, R.anim.slide_left_out);
		slideRightIn = AnimationUtils
				.loadAnimation(this, R.anim.slide_right_in);
		slideRightOut = AnimationUtils.loadAnimation(this,
				R.anim.slide_right_out);

		gestureScanner = new GestureDetector(new MyGestureDetector());

		Utils.onActivityCreateSetTheme(this);
		InitializeTabs();

		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		
	}

	private void ProcessExtras() {

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			String favID = extras.getString("fromShorcut");
			if (favID != null) {
				mainConsultIntent.putExtra("fromShorcut", favID);
			}
		}

	}

	class MyGestureDetector extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {

			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;

				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

					viewFlipper.setInAnimation(slideLeftIn);
					viewFlipper.setOutAnimation(slideLeftOut);
					viewFlipper.showNext();

					changeLtoR();
				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {

					viewFlipper.setInAnimation(slideRightIn);
					viewFlipper.setOutAnimation(slideRightOut);
					viewFlipper.showPrevious();
					changeRtoL();
				}

			} catch (Exception ex) {
			}
			return false;
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		if (gestureScanner != null) {
			if (gestureScanner.onTouchEvent(ev))
				return true;
		}
		return super.dispatchTouchEvent(ev);
	}

	@Override
	public boolean onTouchEvent(MotionEvent me) {
		return gestureScanner.onTouchEvent(me);
	}

	private void changeRtoL() {

		TabHost tabHost = getTabHost();
		int curTab = tabHost.getCurrentTab();
		int nextTab = ((curTab - 1) % 3);
		tabHost.setCurrentTab(nextTab);

		mainHeaderFav.setVisibility(View.VISIBLE);
		mainHeaderCon.setVisibility(View.GONE);
	}

	private void changeLtoR() {

		TabHost tabHost = getTabHost();
		int curTab = tabHost.getCurrentTab();
		int nextTab = ((curTab + 1) % 3);
		tabHost.setCurrentTab(nextTab);

		mainHeaderFav.setVisibility(View.GONE);
		mainHeaderCon.setVisibility(View.VISIBLE);
	}

	/** Initialize all tabs with intent **/
	private void InitializeTabs() {

		Resources res = getResources(); // Resource object to get Drawables
		TabHost tabHost = getTabHost(); // The activity TabHost
		TabHost.TabSpec spec; // Resusable TabSpec for each tab

		mainConsultIntent = new Intent().setClass(this, MainConsult.class);
		ProcessExtras();
		
		spec = tabHost
				.newTabSpec("cuandoLlega")
				.setIndicator(res.getString(R.string.tabTitleCuandoLlega),
						res.getDrawable(R.drawable.timg_cuando))
				.setContent(mainConsultIntent);
		tabHost.addTab(spec);

		
		Intent intent; // Reusable Intent for each tab

		// Create an Intent to launch an Activity for the tab (to be reused)
		intent = new Intent().setClass(this, Favourites.class);

		// Initialize a TabSpec for each tab and add it to the TabHost
		spec = tabHost
				.newTabSpec("Favorites")
				.setIndicator(res.getString(R.string.tabTitleFavourites),
						res.getDrawable(R.drawable.timg_favourite))
				.setContent(intent);
		tabHost.addTab(spec);

		tabHost.setCurrentTab(0);

		tabHost.getTabWidget().getChildAt(1).setVisibility(View.GONE);
		tabHost.getTabWidget().getChildAt(0).setVisibility(View.GONE);
	}

	/*
	 * Create context menu for all aplication
	 * 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateContextMenu(android.view.ContextMenu,
	 * android.view.View, android.view.ContextMenu.ContextMenuInfo)
	 */
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, R.menu.optionsmenu, 0, "Edit");

	}

	/*
	 * Create option menu for all aplication
	 * 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onCreateOptionsMenu(android.view.Menu)
	 */
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.optionsmenu, menu);
		return true;
	}

	/*
	 * Switch each item menu
	 * 
	 * (non-Javadoc)
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.exit:
			System.exit(0);
			return true;
		case R.id.sendSMS:
			SendSMS();
			return true;
		case R.id.preferences:
			StartPreferences();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	public void StartPreferences() {
		Intent settingsActivity = new Intent(getBaseContext(),
				GeneralPreferences.class);
		startActivity(settingsActivity);
	}

	/**
	 * Method to send SMS request
	 */
	public void SendSMS() {
		Bundle extras = mainConsultIntent.getExtras();
		String linea = "";
		String nroParada = "";

		try {
			linea = extras.getString("linea_Key");
			nroParada = extras.getString("nro_Key");

			if ((linea == null || linea.length() == 0 || linea
					.contains(Main.this.getString(R.string.seleccione)))
					|| (nroParada == null || nroParada.length() == 0)) {
				CustomToast toast = new CustomToast(Main.this);
				toast.ShowToast(Main.this
						.getString(R.string.debeElegirLineaYNro));
				return;
			}

			Intent sendIntent = new Intent(Intent.ACTION_VIEW);
			sendIntent.setData(Uri.parse("sms:22522"));
			sendIntent.putExtra("sms_body", "TUP " + nroParada + " " + linea);
			startActivity(sendIntent);

			System.exit(0);

		} catch (Exception e) {
			CustomToast toast = new CustomToast(Main.this);
			toast.ShowToast(Main.this.getString(R.string.errorSMS));
			return;
		}
	}
}
